<script setup lang="ts">
import { reactive, ref, Ref, watch, computed, onMounted } from "vue"
import { Search, Refresh } from "@element-plus/icons-vue"
import Table from "@/components/Table/index.vue"
import { propsList, modalPropsList } from "./config"
import Modal from "@/components/modal/index.vue"
import { getDeviceListApi, editDeviceApi, delDeviceApi, quickDeviceApi } from "@/api/infusion/index"
import { useTagsViewStore } from "@/store/modules/tags-view"
import { storeToRefs } from "pinia"
import { ElMessage } from "element-plus"
import { useMqttStore } from "@/store/modules/mqtt"
import { type IDeviceListData } from "@/api/infusion/types/index"
import { useServer } from "@/hooks/useServer"

enum DEVICETYPE {
  /** 输液 */
  INFUSION = 1,
  /** 无线 */
  WIRELESS = 2
}

interface IFrom {
  page_index: number
  page_size: number
  data_sum: number
  keyword: string
  is_binding: number | string
}

interface IOptions {
  label: string
  value: number
}

const server = useServer()
const tagsViewStore = useTagsViewStore()
const mqttStore = useMqttStore()
const { partition } = storeToRefs(tagsViewStore)
const numOptions: IOptions[] = [
  {
    label: "已编号",
    value: 1
  },
  {
    label: "未编号",
    value: 0
  }
]

const tableData = ref<IDeviceListData[]>([])
const tableRef: Ref<typeof Table | null> = ref(null)

const mateModalRef: Ref<typeof Modal | null> = ref(null)
const selectNumOptions = ref(numOptions)
const hasSelected = ref<IDeviceListData[]>([])

const searchParamsForm = reactive<IFrom>({
  page_index: 1,
  page_size: 10,
  data_sum: 0,
  keyword: "",
  is_binding: ""
})

const handleSearch = () => {
  searchParamsForm.page_index = 1
  searchParamsForm.page_size = 10
  getDeviceList()
}

const resetSearch = () => {
  searchParamsForm.keyword = ""
  searchParamsForm.is_binding = ""
  getDeviceList()
}

const handleMate = () => {
  mqttStore.subscribe("lot/web/get/alarm")
  ;(mateModalRef as Ref<typeof Modal>).value.showModal()
}

const handleDel = async (row: IDeviceListData) => {
  const params = {
    area_id: partition.value as number,
    device_code: [row.device_code]
  }
  const res = await delDeviceApi(params)
  const { result, return_message } = res

  if (result === 200) {
    ElMessage.success("删除成功")
    tableRef.value?.clearSelected()

    getDeviceList()
  } else {
    ElMessage.error(return_message)
  }
}

//正则检验
const checkSpace = (value: string) => {
  // eslint-disable-next-line no-useless-escape
  const regex = /^[^\s!@#$%^&*()_+={}\[\]:;"'<>,.?\\/]*$/
  const flag = regex.test(value)
  return !flag
}

// 编辑/保存
const handleEdit = async (row: IDeviceListData) => {
  const { device_name } = row

  const flag = checkSpace(device_name)

  if (flag) {
    return ElMessage.error("设备名称不可输入空格和特殊字符")
  }

  row.is_eidt = !row.is_eidt

  // 保存
  if (!row.is_eidt) {
    try {
      const { sort, device_code } = row
      const params = {
        area_id: partition.value as number,
        sort,
        device_name,
        device_code
      }

      const res = await editDeviceApi(params)

      const { result, return_message } = res
      if (result === 200) {
        ElMessage.success("修改成功")
        getDeviceList()
      } else {
        ElMessage.error(return_message)
      }
    } catch (error) {
      console.info(error)
    }
  }
}

const handleChangePage = (page: number) => {
  searchParamsForm.page_index = page
  getDeviceList()
}

const handleChangeSize = (size: number) => {
  searchParamsForm.page_size = size
  getDeviceList()
}

const getDeviceList = async () => {
  try {
    const area_id = partition.value
    const { keyword, page_size, page_index, is_binding } = searchParamsForm
    const params = {
      device_type_id: 1,
      area_id,
      keyword,
      page_size,
      page_index,
      is_binding
    }
    const res = await getDeviceListApi(params)
    const { data, result, return_message } = res

    if (result === 200) {
      const { data: deviceData, data_sum, page_index, page_size } = data
      tableData.value = deviceData
      searchParamsForm.data_sum = data_sum
      searchParamsForm.page_index = page_index
      searchParamsForm.page_size = page_size
    } else {
      ElMessage.error(return_message)
    }
  } catch (error) {
    console.info(error)
  }
}

const handleSave = async () => {
  try {
    const devices = quickTable.value.map((item) => {
      const { device_code, device_name, sort } = item
      return {
        device_name,
        device_code,
        sort: sort
      }
    })
    const params = {
      area_id: partition.value as number,
      device_type_id: 1,
      devices
    }
    const res = await quickDeviceApi(params)

    const { result, return_message } = res
    if (result === 200) {
      ElMessage.success("保存成功")
      handleCloseMate()
      getDeviceList()
    } else {
      ElMessage.error(return_message)
    }
  } catch (error) {
    console.info(error)
  }
}

const handleCloseMate = () => {
  ;(mateModalRef as Ref<typeof Modal>).value.closeModal()
  mqttStore.resetQuickData()
}

const quickTable = computed(() => mqttStore.quickTableData)

// 批量删除
const handleBatchDel = async () => {
  const device_code = hasSelected.value.map((item) => item.device_code)
  const params = {
    area_id: partition.value as number,
    device_code
  }
  const res = await delDeviceApi(params)
  const { result, return_message } = res
  if (result === 200) {
    ElMessage.success("删除成功")
    tableRef.value?.clearSelected()

    getDeviceList()
  } else {
    ElMessage.error(return_message)
  }
}

// 选中
const handleSelect = (selected: IDeviceListData[]) => {
  hasSelected.value = selected
}

const handleClickLink = () => {
  const domainName = server.replace(/:\d+$/, "")
  const url = `${domainName}:10082/analysis-panel?area_id=${partition.value}`
  window.open(url)
}

watch(
  () => partition.value,
  () => {
    getDeviceList()
  }
)

onMounted(() => {
  getDeviceList()
})
</script>

<template>
  <div>
    <!-- 搜索框 -->
    <div flex justify-between bg-white items-center p-15px rounded-5px mb-15px>
      <div flex items-center>
        <el-form w-995px ref="searchFormRef" :inline="true" :model="searchParamsForm">
          <el-form-item prop="keyword">
            <el-input
              class="w-250px!"
              v-model="searchParamsForm.keyword"
              placeholder="请输入设备名称/呼叫码/接收器IP"
            />
          </el-form-item>

          <el-form-item prop="num">
            <el-select
              clearable
              v-model="searchParamsForm.is_binding"
              placeholder="请选择是否编号"
              style="width: 240px"
            >
              <el-option v-for="item in selectNumOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="bg-#387af6!" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button type="primary" :icon="Refresh" class="bg-#387af6!" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div>
        <el-button
          :disabled="!hasSelected.length"
          @click="handleBatchDel"
          type="primary"
          :class="
            !hasSelected.length
              ? 'bg-#f5f5f5! border-#d9d9d9! text-#00000040!'
              : 'bg-#ff7875! text-white! border-#ff7875!'
          "
          >批量删除</el-button
        >
        <el-button @click="handleMate" type="primary" class="bg-#387af6!">匹配模式</el-button>
        <el-button title="点击打开状态展示页面链接" @click="handleClickLink" type="success" class="bg-#387af6!"
          >状态展示页面链接</el-button
        >
      </div>
    </div>

    <!-- 表格 -->
    <Table
      ref="tableRef"
      :index="true"
      :total="searchParamsForm.data_sum"
      :show-check-box="true"
      :select-width="60"
      :data="tableData"
      :props-list="propsList"
      indexName="编号"
      @change-page="handleChangePage"
      @change-size="handleChangeSize"
      @select="handleSelect"
    >
      <template #type="{ row }">
        <div>
          <span>{{ row.device_type_id === DEVICETYPE.INFUSION ? "智能输液" : "无线报警" }}</span>
        </div>
      </template>

      <template #name="{ row }">
        <div>
          <el-input maxlength="5" v-if="row.is_eidt" v-model="row.device_name" />
          <span v-else cursor-pointer>{{ row.device_name }}</span>
        </div>
      </template>

      <template #handler="{ row }">
        <div flex>
          <span cursor-pointer class="text-#387af6!" @click="handleEdit(row)">{{ row.is_eidt ? "保存" : "编辑" }}</span>
          <span ml-20px cursor-pointer class="text-#FF4C4C!" @click="handleDel(row)">删除</span>
        </div>
      </template>
    </Table>

    <Modal title="匹配模式" ref="mateModalRef" width="920">
      <template #content>
        <div>
          <header>
            <div flex>
              <span ml-10px mb-10px>
                匹配模式说明：单击报警器呼叫按钮即可添加信息，重复添加无效，设备编号从1开始计算按顺位进行补缺填入，若误触误按需返回设备列表进行删除后重新添加。
              </span>
            </div>
          </header>

          <Table
            :show-paging="false"
            class="mate_conatiner"
            max-height="450px"
            :total="30"
            :show-check-box="false"
            :data="quickTable"
            :props-list="modalPropsList"
          >
            <template #name="{ row }">
              <div>
                <el-input maxlength="5" class="w-120px!" v-model="row.device_name" />
              </div>
            </template>
          </Table>
        </div>
      </template>

      <template #footer>
        <div pr-20px>
          <el-button class="w-105px!" @click="handleCloseMate">取消</el-button>
          <el-button :disabled="!quickTable.length" class="w-105px! bg-#387af6!" type="primary" @click="handleSave">
            保存
          </el-button>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0px;
}

:deep(.el-dialog) {
  padding-left: 0;
  padding-right: 0;
  padding-top: 0;
  border-radius: 5px;
  background: #f7f9fb;

  .el-dialog__body {
    padding: 20px;
  }
}

.mate_conatiner {
  :deep(.el-table__row) {
    height: 50px !important;
  }
}
</style>
